﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using mitasoft.Web.DAL;
using MySite2.Services;
using StructureMap;
using mitasoft.Web.Common.Interface;

namespace MySite2
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        #region fields

        ILogger logger = null;
        IConfig config = null;

        #endregion


        #region ctor

        public MvcApplication()
        {
            InitDI();
            log4net.Config.XmlConfigurator.Configure();

            logger = ObjectFactory.GetInstance<ILogger>();
            config = ObjectFactory.GetInstance<Services.IConfig>();

            this.Error += (o, e) =>
            {
                logger.Instance.Error(Server.GetLastError());
                Server.ClearError();
            };
        }

        #endregion


        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //routes.MapPageRoute(
            //    "AdminSpecificRoute", 
            //    "admin/",
            //    "~/admin/pages/index.aspx"
            //);

            //Custom route for reports
            routes.MapPageRoute(
                "AdminRoute",                         // Route name
                "Admin/Pages/{pagename}",             // URL
                "~/Admin/Pages/{pagename}"            // File
           );


            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            InitDatabaseModel();

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            //Set current Controller factory as StructureMapControllerFactory
            ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
        }



        #region private methods

        /// <summary>
        /// Init DI container
        /// </summary>
        private void InitDI()
        {
            Infrastructure.InitDI.Register();
        }

        /// <summary>
        /// Try to update current database
        /// </summary>
        private void InitDatabaseModel()
        {
            try
            {
                if (config.ReinitDatabase)
                {
                    InitializeModel.Init();
                }
            }
            catch (Exception ex)
            {
                logger.Instance.Error(ex);
            }
        }

        #endregion

    }

    public class StructureMapControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            try
            {
                if (controllerType != null)
                {
                    return ObjectFactory.GetInstance(controllerType) as Controller;
                }

                return null;
            }
            catch (StructureMapException)
            {
                System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
                throw;
            }
        }
    }
}